//
//  XLMatchViewController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2018/1/25.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLMatchViewController.h"
#import <Masonry.h>
#import <UtilsMacro.h>
 
#import <ImSDK/TIMGroupManager.h>
#import <ImSDK/TIMFriendshipManager.h>
#import <ReactiveCocoa.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLHTTPSessionManager+Camgirl.h"
#import "CallMakeViewController.h"
#import <UIViewController+TopViewController.h>
#import "TopUpViewController.h"

#define RippleAnimationAvatarSize CGSizeMake(88, 88)
#define RippleAnimationExpandSizeValue 50.0
#define RippleAnimationDuration 2.0
#define RippleAnimationLineWidth 1.0

@interface XLMatchViewController ()
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIImageView *userAvatarView;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, copy) NSString *matchId;
@property (nonatomic, weak) RACDisposable *matchDisposable;
@property (nonatomic, weak) RACDisposable *observerDisposable;
@property (nonatomic, weak) NSTimer *timer;
@property (nonatomic, strong) NSArray *anchorArray;

@property (nonatomic, strong) UIImageView *avatar1;
@property (nonatomic, strong) UIImageView *avatar2;
@property (nonatomic, strong) UIImageView *avatar3;
@property (nonatomic, strong) UIImageView *avatar4;
@property (nonatomic, strong) UIImageView *avatar5;
@property (nonatomic, strong) UIImageView *avatar6;
@property (nonatomic, strong) UIImageView *avatar7;
@end

@implementation XLMatchViewController {
    UIBezierPath *_initPath;
    UIBezierPath *_finalPath;
    UIView      *_avatarWrapView;
    NSInteger   _second;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userId = [[XLAccountManager shareInstance] model].Id;
    [self setupView];
    [self requestMatch];
    [self setupTimer];
    [self getOnlineAnchor];
    [self addObserver];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _initPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(0, 0, RippleAnimationAvatarSize.width, RippleAnimationAvatarSize.height), RippleAnimationLineWidth, RippleAnimationLineWidth)];
    _finalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(- RippleAnimationExpandSizeValue, - RippleAnimationExpandSizeValue, RippleAnimationAvatarSize.width + RippleAnimationExpandSizeValue * 2, RippleAnimationAvatarSize.height + RippleAnimationExpandSizeValue * 2), RippleAnimationLineWidth, RippleAnimationLineWidth)];
    
    [self beginAnimation];
}

- (void)dealloc {
    [self.matchDisposable dispose];
    [self.observerDisposable dispose];
}

- (void)addObserver {
    @weakify(self);
    self.observerDisposable = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"QiangDanNotification" object:nil] subscribeNext:^(NSNotification *notification) {
        @strongify(self);
        if ([UIViewController topViewController] != self) return ;
        TIMMessage *msg = notification.object;
        TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
        
        if ([[NSString stringWithFormat:@"%@",dic[@"oppositeUserId"]] isEqualToString:self.userId] && [[NSString stringWithFormat:@"%@",dic[@"orderNum"]] isEqualToString:self.matchId]) {
            [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:msg.sender userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
                @strongify(self);
                NSString * callID =  F(@"%@", x[@"CallId"]);
                CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
                make.IsOneTimeCall = [x[@"IsOneTimeCall"] boolValue];
                make.UserFreeSecond = [x[@"UserCardSecond"] intValue];
                make.peerId = [NSString stringWithFormat:@"%@",msg.sender];
                make.headStr = dic[@"headimg"];
                make.nickNameStr = dic[@"name"];
                make.detailStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"job"]];
                make.addressStr = dic[@"address"];
                make.ageStr = [dic[@"age"] integerValue];
                make.jobStr = dic[@"job"];
                make.ismic = YES;
                make.iscinema = YES;
                make.callid = callID;
                make.videoid = [NSString stringWithFormat:@"%@",callID];
                make.moneyStr = @"20";
                make.gradeStr = [NSString stringWithFormat:@"%@",dic[@"leval"]];
                make.isAuto = YES;
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:make animated:YES completion:nil];
                [self quitGroup];
                [self quitMatch];
                [self.navigationController popViewControllerAnimated:NO];
                
            } error:^(NSError *error) {
                @strongify(self);
                NSLog(@"%@", error);
                if (error.code == 6) {  //余额不足
                    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                    topVC.In_purchase = isIn_purchase;
                    [self.navigationController pushViewController:topVC animated:YES];
                } else {  //被拉入黑名单//对方已屏蔽视聊
                    [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                }
            }];
        }
    }];
}

- (void)setupTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction {
    _second++;
    self.timeLabel.text = F(@"已等待 %@", [self playProgressHourMinuteSeconds:_second]);
}

- (void)requestMatch {
    self.matchDisposable = [[[XLHTTPSessionManager sharedManager] requestMatchingWithUserId:self.userId] subscribeNext:^(id x) {
        if ([[x objectForKey:@"result"] boolValue]) {
            self.matchId = x[@"matchId"];
            [self joinGroup];
        } else {
            [MBProgressHUD showContent:x[@"msg"] ?: @"匹配失败，请稍后再试" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } error:^(NSError *error) {
        [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    }];
}

- (void)quitMatch {
    NSString *userid = [UserDefaults objectForKey:UserID];
    
    [[[XLHTTPSessionManager sharedManager] quitMatchingWithUserId:userid] subscribeNext:^(id x) {
        
    } error:^(NSError *error) {
        
    }];
}

- (void)joinGroup {
    [[TIMGroupManager sharedInstance] JoinGroup:@"10086" msg:@"" succ:^{
        [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"0" succ:^{
        } fail:^(int code, NSString *msg) {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    } fail:^(int code, NSString *msg) {
        if (code == 10013) {
            [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"0" succ:^{
            } fail:^(int code, NSString *msg) {
                [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }];
        } else {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

- (void)quitGroup {
    [[TIMGroupManager sharedInstance] QuitGroup:@"10086" succ:^{
        
    } fail:^(int code, NSString *msg) {
        
    }];
}

- (void)getOnlineAnchor {
    [[[XLHTTPSessionManager sharedManager] getOnlineAnchor] subscribeNext:^(id x) {
        self.anchorArray = x;
        NSMutableArray *arr = self.anchorArray.mutableCopy;
        self.anchorArray = arr.copy;
        NSString *text = F(@"已为您邀请%zd位女神", self.anchorArray.count);
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:[text rangeOfString:F(@"%zd", self.anchorArray.count)]];
        self.tipLabel.attributedText = str;
        for (NSInteger i = 0; i < self.anchorArray.count; i++) {
            NSDictionary *dic = self.anchorArray[i];
            switch (i) {
                case 0: {
                    [self.avatar1 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                    [UIView animateWithDuration:0.5 animations:^{
                        self.avatar1.alpha = 1;
                    }];
                }
                    break;
                case 1: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar2 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar2.alpha = 1;
                        }];
                    });
                }
                    break;
                case 2: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar3 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar3.alpha = 1;
                        }];
                    });
                }
                    break;
                case 3: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar4 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar4.alpha = 1;
                        }];
                    });
                }
                    break;
                case 4: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar5 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar5.alpha = 1;
                        }];
                    });
                }
                    break;
                case 5: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar6 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar6.alpha = 1;
                        }];
                    });
                }
                    break;
                case 6: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i + ((arc4random() % 20) / 10.0 - 1)) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.avatar7 setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
                        [UIView animateWithDuration:0.5 animations:^{
                            self.avatar7.alpha = 1;
                        }];
                    });
                }
                    break;
                    
                default:
                    break;
            }
        }
    } error:^(NSError *error) {
        
    }];
}

- (void)setupView {
    self.fd_prefersNavigationBarHidden = YES;
    self.fd_interactivePopDisabled = YES;
    UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:F(@"supei_bg_dibu_%.0f_%.0f", ScreenWidth * [UIScreen mainScreen].scale, ScreenHeight * [UIScreen mainScreen].scale)]];
    [self.view addSubview:backgroundView];
    [backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    UIButton *backButton = [[UIButton alloc] init];
    [backButton setImage:[UIImage imageNamed:@"supei_nav_but_chacha_n"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(24, 24));
        make.left.equalTo(self.view.mas_left).offset(19);
        if (IS_IPHONE_X) {
            make.top.equalTo(self.view.mas_top).offset(54);
        } else {
            make.top.equalTo(self.view.mas_top).offset(30);
        }
    }];
    
    UIView *tipContentView = [[UIView alloc] init];
    tipContentView.backgroundColor = HEXCOLOR(0x321354);
    tipContentView.layer.borderColor = RGB(72, 67, 107).CGColor;
    tipContentView.layer.borderWidth = 1;
    tipContentView.layer.cornerRadius = 25;
    [self.view addSubview:tipContentView];
    [tipContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(200, 50));
        make.top.equalTo(backButton.mas_bottom).offset(20);
    }];
    
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.textColor = [UIColor whiteColor];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.text = @"美女正在接听，请稍等...";
    [tipContentView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipContentView.mas_top).offset(6);
        make.centerX.equalTo(tipContentView);
    }];
    
    _timeLabel = [[UILabel alloc] init];
    _timeLabel.font = [UIFont systemFontOfSize:12];
    _timeLabel.textColor = RGB(193, 184, 203);
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.text = @"已等待 00:00";
    [tipContentView addSubview:_timeLabel];
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(tipContentView.mas_bottom).offset(-6);
        make.centerX.equalTo(tipContentView);
    }];
    
    UIView *centerCircleView = [[UIView alloc] init];
    centerCircleView.backgroundColor = RGB(96, 25, 90);
    centerCircleView.layer.cornerRadius = ceil(ScreenWidth * 0.6) / 2.0;
    [self.view addSubview:centerCircleView];
    [centerCircleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view).centerOffset(CGPointMake(0, 20));
        make.size.mas_equalTo(CGSizeMake(ceil(ScreenWidth * 0.6), ceil(ScreenWidth * 0.6)));
    }];
    
    _avatarWrapView = [[UIView alloc] init];
    [self.view addSubview:_avatarWrapView];
    [_avatarWrapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view).centerOffset(CGPointMake(0, 20));
        make.size.mas_equalTo(RippleAnimationAvatarSize);
    }];
    
    _userAvatarView = [[UIImageView alloc] init];
    _userAvatarView.layer.cornerRadius = 44;
    _userAvatarView.layer.masksToBounds = YES;
    [_userAvatarView setImageWithURL:[NSURL URLWithString:[[XLAccountManager shareInstance] model].HeadImg] placeholder:nil];
    [_avatarWrapView addSubview:_userAvatarView];
    [_userAvatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_avatarWrapView);
    }];
    
    _avatar1 = [[UIImageView alloc] init];
    _avatar1.layer.cornerRadius = 30;
    _avatar1.layer.masksToBounds = YES;
    _avatar1.layer.borderWidth = 2;
    _avatar1.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar1.alpha = 0;
    [self.view addSubview:_avatar1];
    [_avatar1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(100);
        make.bottom.equalTo(centerCircleView.mas_top).offset(-15);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _avatar2 = [[UIImageView alloc] init];
    _avatar2.layer.cornerRadius = 30;
    _avatar2.layer.masksToBounds = YES;
    _avatar2.layer.borderWidth = 2;
    _avatar2.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar2.alpha = 0;
    [self.view addSubview:_avatar2];
    [_avatar2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_userAvatarView.mas_right).offset(25);
        make.top.equalTo(centerCircleView.mas_top).offset(36);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];

    _avatar3 = [[UIImageView alloc] init];
    _avatar3.layer.cornerRadius = 30;
    _avatar3.layer.masksToBounds = YES;
    _avatar3.layer.borderWidth = 2;
    _avatar3.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar3.alpha = 0;
    [self.view addSubview:_avatar3];
    [_avatar3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(centerCircleView.mas_top).offset(160);
        make.left.equalTo(self.view.mas_left).offset(70);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _avatar4 = [[UIImageView alloc] init];
    _avatar4.layer.cornerRadius = 30;
    _avatar4.layer.masksToBounds = YES;
    _avatar4.layer.borderWidth = 2;
    _avatar4.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar4.alpha = 0;
    [self.view addSubview:_avatar4];
    [_avatar4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-88);
        make.bottom.equalTo(centerCircleView.mas_top).offset(-15);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _avatar5 = [[UIImageView alloc] init];
    _avatar5.layer.cornerRadius = 30;
    _avatar5.layer.masksToBounds = YES;
    _avatar5.layer.borderWidth = 2;
    _avatar5.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar5.alpha = 0;
    [self.view addSubview:_avatar5];
    [_avatar5 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(25);
        make.top.equalTo(centerCircleView.mas_top);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _avatar6 = [[UIImageView alloc] init];
    _avatar6.layer.cornerRadius = 30;
    _avatar6.layer.masksToBounds = YES;
    _avatar6.layer.borderWidth = 2;
    _avatar6.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar6.alpha = 0;
    [self.view addSubview:_avatar6];
    [_avatar6 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-100);
        make.top.equalTo(centerCircleView.mas_top).offset(ceil(ScreenWidth * 0.6));
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _avatar7 = [[UIImageView alloc] init];
    _avatar7.layer.cornerRadius = 30;
    _avatar7.layer.masksToBounds = YES;
    _avatar7.layer.borderWidth = 2;
    _avatar7.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatar7.alpha = 0;
    [self.view addSubview:_avatar7];
    [_avatar7 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-25);
        make.top.equalTo(centerCircleView.mas_top).offset(140);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    _tipLabel = [[UILabel alloc] init];
    _tipLabel.font = [UIFont systemFontOfSize:14];
    _tipLabel.textColor = [UIColor whiteColor];
    _tipLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_avatar6.mas_bottom).offset(20);
        make.centerX.equalTo(self.view);
    }];
}

#pragma mark - Action
- (void)backAction {
    [self quitGroup];
    [self quitMatch];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)playProgressHourMinuteSeconds:(NSInteger)seconds {
    NSMutableString *tempStr = [[NSMutableString alloc] init];
    if (seconds < 60) {
        [tempStr appendString:F(@"00:%02zd", seconds)];
    } else if (seconds >= 60) {
        NSInteger second = seconds % 60; // 秒
        NSInteger minutes = seconds / 60; // 分
        if (minutes < 60) {
            [tempStr appendString:F(@"%02zd:%02zd", minutes, second)];
        } else {
            NSInteger hours = minutes / 60; // 时
            NSInteger minute = minutes % 60; // 分
            [tempStr appendString:F(@"%02zd:%02zd:%02zd", hours, minute, second)];
        }
    }
    return tempStr.mutableCopy;
}

- (void)animationReplicatorAvatarInView:(UIView *)view animated:(BOOL)animated {
    
    NSMutableArray *_layers = [[NSMutableArray alloc] init];
    NSInteger count = view.layer.sublayers.count;
    for (int i = 0; i < count; i++) {
        if ([view.layer.sublayers[i] isKindOfClass:[CAReplicatorLayer class]]) {
            [_layers addObject:view.layer.sublayers[i]];
            [view.layer.sublayers[i] setHidden:YES];
        }
    }
    count = _layers.count;
    for (int i = 0; i < count; i++) {
        [_layers[i] removeFromSuperlayer];
    }
    
    if (!animated) {
        return;
    }
    
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    replicatorLayer.instanceCount = 3;
    replicatorLayer.instanceDelay = 2.0 / 3;
    replicatorLayer.backgroundColor = [UIColor clearColor].CGColor;
    [view.layer addSublayer:replicatorLayer];
    
    CAShapeLayer *layer = [self animationLayerWithPath:_initPath];
    layer.frame = CGRectMake(0, 0, RippleAnimationAvatarSize.width, RippleAnimationAvatarSize.height);
    [replicatorLayer addSublayer:layer];
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    pathAnimation.fromValue = (id)_initPath.CGPath;
    pathAnimation.toValue = (id)_finalPath.CGPath;
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = @1;
    opacityAnimation.toValue = @0;
    
    CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
    groupAnimation.animations = @[pathAnimation, opacityAnimation];
    groupAnimation.duration = RippleAnimationDuration;
    groupAnimation.repeatCount = HUGE_VALF;
    
    [layer addAnimation:groupAnimation forKey:nil];
}

- (CAShapeLayer *)animationLayerWithPath:(UIBezierPath *)path {
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor whiteColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = RippleAnimationLineWidth;
    return layer;
}

- (void)beginAnimation {
    [self animationReplicatorAvatarInView:_avatarWrapView animated:YES];
    [_avatarWrapView bringSubviewToFront:_userAvatarView];
}
@end
